package pers.llc.css.excutor;

import java.util.concurrent.*;


/**
 * @author lls
 * @time 2018-10-01
 */
public class ThreadPoolDeadLockAvoidance {
    private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            1,
            1,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<>(),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    public void test(final String mes) {
        Runnable taskA = () -> {
            System.out.println("Executing taskA");
            Runnable taskB = () -> System.out.println("TaskB processes " + mes);
            Future<?> rs = threadPoolExecutor.submit(taskB);
            try {
                System.out.println("rs.get()");
                rs.get();   //等待taskB执行
                System.out.println("rs.get() over" + rs.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println("TaskA Done");
        };
        System.out.println("submit sa");
        threadPoolExecutor.submit(taskA);
        System.out.println("submit sb");
    }

    public static void main(String[] args) {
        ThreadPoolDeadLockAvoidance poolDeadLockAvoidance = new ThreadPoolDeadLockAvoidance();
        poolDeadLockAvoidance.test("TEST MESSAGE");
        System.out.println("main thread over");
    }
}
